package com.luoboduner.moo.info.util;

import cn.hutool.json.JSONException;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.luoboduner.moo.info.App;
import com.luoboduner.moo.info.bean.CommonConfig;
import com.luoboduner.moo.info.bean.MonSubjectBo;
import com.luoboduner.moo.info.ui.form.OverviewForm;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

/**
 * @version V2.3
 * @ClassName:RestUtil.java
 * @author: wgcloud
 * @date: 2019年11月16日
 * @Description: RestUtil.java
 * @Copyright: 2017-2024 www.wgstart.com. All rights reserved.
 */
public class RestUtil {

  private static final RestTemplate restTemplate = new RestTemplate();
  private static final CommonConfig commonConfig = new CommonConfig();

  private static String getBaseUrl(String url) {
    return "http://"+App.config.getServerIp()+":"+App.config.getPort() + url;
  }
  public static JSONObject post(String url, JSONObject obj, String className) {
    try {
      JSONObject jsonObject = new JSONObject();
      jsonObject.put("dmToken", MD5Utils.GetMD5Code(commonConfig.getDmToken()));
      jsonObject.put(className, obj);
      HttpHeaders headers = new HttpHeaders();
      headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
      headers.add("Accept", MediaType.APPLICATION_JSON_UTF8.toString());
      HttpEntity<String> httpEntity = new HttpEntity<>(JSONUtil.parse(jsonObject).toString(), headers);
      ResponseEntity<String> responseEntity = restTemplate.postForEntity(getBaseUrl(url) , httpEntity, String.class);
      OverviewForm.getInstance().setServerOnline(true);
      return JSONUtil.parseObj(responseEntity.getBody());
    } catch (JSONException e) {
      return new JSONObject(e.getMessage());
    }
  }

  public static JSONObject get(String url) throws Exception {
    try {
      ResponseEntity<String> responseEntity = restTemplate.getForEntity(getBaseUrl(url), String.class);
      OverviewForm.getInstance().setServerOnline(true);
      return JSONUtil.parseObj(responseEntity.getBody());
    } catch (Exception e) {
      OverviewForm.getInstance().setServerOnline(false);
      throw new Exception(e.getMessage());
    }
  }

}
